package com.android.example.app3;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class ImageSaver {

    private static final String TAG = "ImageSaver";
    private final Context context;

    public ImageSaver(Context context) {
        this.context = context;

    }

    public void saveCapturedImageToPtFolder(String fileNameBase, Bitmap mutableBitmap) {


        String timeStamp = new SimpleDateFormat("MMdd_HHmmss", Locale.getDefault()).format(new Date());
        String timeStamp1 = new SimpleDateFormat("yyyyMM", Locale.getDefault()).format(new Date());
        String fileName = fileNameBase + "_" + timeStamp + ".jpg";

        ContentValues contentValues = new ContentValues();
        contentValues.put(MediaStore.Images.Media.DISPLAY_NAME, fileName);
        contentValues.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
        contentValues.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_DCIM + "/" + "LGSAppImages" + "/" + timeStamp1);

        ContentResolver resolver = context.getContentResolver();

        try {
            Uri imageUri = resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, contentValues);
            if (imageUri != null) {
                try (OutputStream os = resolver.openOutputStream(imageUri)) {
                    assert os != null;
                    mutableBitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
                    // 更新UI（在主线程中）
                    MainActivity MainActivity = new MainActivity();
                    MainActivity.updateUiAfterSave(imageUri, fileNameBase);
                    // 通知系统更新媒体库
                    resolver.notifyChange(imageUri, null);
                } catch (IOException e) {
                    Log.e(TAG, "保存图片时发生错误", e);
                    Toast.makeText(context, "保存图片时发生错误", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(context, "保存图片失败", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "保存图片时发生错误", e);
            Toast.makeText(context, "保存图片时发生错误", Toast.LENGTH_SHORT).show();
        }
    }

}